package org.dizena.utils;

import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class CdnAuthUrlUtil
{

    public static String makeCdnUrl(String url)
    {
        String uri = getAction(url);
        long ts = System.currentTimeMillis() / 1000;
        if (url.contains("cdn.bcebos"))
        {
            ts = ts + 15;
        }
        else
        {
            ts = ts - 1785;
        }
        String rand = StrUtil.makeNumCode();
        String sk = "HuiYeOss3DSMainKey";
        String str = uri + "-" + ts + "-" + rand + "-0-" + sk;
        String md5hash = DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8));
        return url + "?auth_key=" + ts + "-" + rand + "-0-" + md5hash;
    }


    private static String getAction(String url)
    {
        int j11 = url.indexOf("//");
        int i11 = url.indexOf("/", j11 + 2);

        String action = url.substring(i11, url.length());
        int k11 = url.indexOf("?");
        if (k11 > 0)
        {
            action = url.substring(i11, k11);
        }
        return action;
    }

    private static String md5(String src) {
        try {
            // 加密对象，指定加密方式
            MessageDigest md5 = MessageDigest.getInstance("md5");
            // 准备要加密的数据
            byte[] b = src.getBytes();
            // 加密
            byte[] digest = md5.digest(b);
            // 十六进制的字符
            char[] chars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
            StringBuffer sb = new StringBuffer();
            // 处理成十六进制的字符串(通常)
            for (byte bb : digest) {
                sb.append(chars[(bb >> 4) & 15]);
                sb.append(chars[bb & 15]);
            }
            // 打印加密后的字符串
            return sb.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


}
